package com.buddy.learn.javasource._thread;

import java.util.concurrent.TimeUnit;

/**
 * @author Buddy
 * @date 2021/5/14
 */
public class _ThreadGroup {

    public static void main(String[] args) throws InterruptedException {
        MyThreadGroup threadGroup = new MyThreadGroup("Buddy");
        for (int i = 0; i < 10; i++) {
            new MyThread(threadGroup, "线程" + i, "1").start();
        }
        TimeUnit.SECONDS.sleep(1);
        //制造一个异常线程
//        new MyThread(threadGroup, "异常线程", "a").start();
        // ThreadGroup 是 Thread 的一个 属性，可以在Thread 的构造方法中传入指定的ThreadGroup。
        // 我们可以通过写一个类继承 ThreadGroup ，然后重写其 uncaughtException，来 interrupt 其他线程；
        // 或者直接调用 threadGroup 的interrupt 方法，注意：有可能会抛出 interrupt 异常(如果在线程调用 sleep方法的时候)。
        System.out.println("------------------------------------------");
        threadGroup.interrupt();

        TimeUnit.SECONDS.sleep(2);
//        //再启一个正常线程
//        new MyThread(threadGroup, "正常线程", "1").start();
    }


    private static class MyThreadGroup extends ThreadGroup {
        MyThreadGroup(String name) {
            super(name);
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            super.uncaughtException(t, e);
            this.interrupt();
        }
    }

    private static class MyThread extends Thread {
        private String number;

        MyThread(MyThreadGroup threadGroup, String name, String number) {
            super(threadGroup, name);
            this.number = number;
        }

        @Override
        public void run() {
            //这步类型转换是要故意制造异常
            int num = Integer.parseInt(number);
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName() + "正在运行...");
            }
            System.out.println(">>>" + Thread.currentThread().getName() + "结束运行!!!");
        }
    }
}
